<template>
	<view class="page">
		<view class="top-warp">
			<zx-nav title="城市选择" bg="#fff"></zx-nav>
			<view>
				<view class="search-bar">
					<view class="search-bar-form">
						<view class="search-bar-box">
							<!-- <icon class="icon-search-in-box" type="search" size="16"></icon> -->
							<input
								confirm-type="search"
								class="search-bar-input"
								placeholder="输入城市名称或首字母查询"
								placeholder-class="phcolor"
								:value="inputVal"
								:focus="inputShowed"
								@input="inputTyping"
							/>
							<view class="icon-clear" v-if="inputVal" @tap="clearInput">
								<!-- #ifdef APP-PLUS || MP -->
								<icon type="clear" :size="15"></icon>
								<!-- #endif -->
							</view>
						</view>
						<label class="search-bar-label" v-if="!inputShowed" @tap="showInput">
							<!-- <icon class="icon-search" type="search" size="16"></icon> -->
							<view class="search-bar-text">输入城市名称或首字母查询</view>
						</label>
					</view>
				</view>
				<view class="flex align-center selectAddr" v-if="!inputShowed">
					<view class=" item" @tap="currIndex = 0" :class="{ 'u-primary': !province }">{{ province || '请选择' }}</view>
					<view class="u-primary item">请选择</view>
				</view>
			</view>
		</view>

		<scroll-view v-if="inputShowed" class="scrollList" scroll-y :style="{ height: winHeight + 'px' }">
			<view class="tui-list search-result">
				<view
					class="tui-list-cell"
					hover-class="tui-list-cell-hover"
					v-for="(item, index) in searchResult"
					:key="index"
					@tap="selectCity(item)"
					:data-name="item"
					:hover-stay-time="150"
				>
					<view class="tui-list-cell-navigate">{{ item.city }}</view>
				</view>
			</view>
		</scroll-view>
		<swiper :current="currIndex" v-if="!inputVal" @change="changeSwiper" :style="{ height: winHeight + 'px' }">
			<swiper-item>
				<scroll-view class="scrollList" scroll-y :scroll-into-view="'p' + scrollViewPronId" :style="{ height: winHeight + 'px' }">
					<view>
						<view class="current-city flex align-center">
							<view class="title">定位城市</view>
							<view class="city-name flex-sub text-cut">
								<tui-icon name="position-fill" color="#5677fc" :size="18"></tui-icon>
								{{ loadAddr ? '定位中...' : locationCity || '定位失败，无权限' }}
							</view>
							<view class="title margin-right-lg" @tap="getLocationAuth">
								<text class="cuIcon-focus"></text>
								重新定位
							</view>
						</view>
						<view v-if="currentLocation" class="current-city" style="padding-top:30rpx;border-top: 1px solid rgb(234, 238, 241);;">
							<text class="title">已选择： {{ currentLocation }}</text>
						</view>

						<view class="tui-list city-list">
							<block v-for="(list, index) in allprovincelist" :key="index" v-if="list.data[0]">
								<view class="tui-list-cell-divider" :id="index === 0 ? 'psuoyin' : 'p' + list.letter">{{ list.letter }}</view>
								<view
									class="tui-list-cell"
									hover-class="tui-list-cell-hover"
									v-for="(item, index2) in list.data"
									:key="index2"
									@tap="selectProvince(item)"
									:data-name="item.cityName"
									:hover-stay-time="150"
								>
									<view class="tui-list-cell-navigate" :class="[list.data.length - 1 == index ? 'last' : '']">{{ item.cityName }}</view>
								</view>
							</block>
						</view>
					</view>
				</scroll-view>
			</swiper-item>
			<swiper-item v-if="province">
				<scroll-view class="scrollList" scroll-y :scroll-into-view="scrollViewId" :style="{ height: winHeight + 'px' }">
					<view>
						<view class="current-city flex align-center">
							<view class="title">定位城市</view>
							<view class="city-name flex-sub text-cut">
								<tui-icon name="position-fill" color="#5677fc" :size="18"></tui-icon>
								{{ loadAddr ? '定位中...' : locationCity || '定位失败，无权限' }}
							</view>
							<view class="title margin-right-lg" @tap="getLocationAuth">
								<text class="cuIcon-focus"></text>
								重新定位
							</view>
						</view>
						<view v-if="currentLocation" class="current-city" style="padding-top:30rpx;border-top: 1px solid rgb(234, 238, 241);;">
							<text class="title">已选择： {{ currentLocation }}</text>
						</view>

						<view class="tui-list city-list">
							<block v-for="(list, index) in lists" :key="index" v-if="list.data[0]">
								<view class="tui-list-cell-divider" :id="index === 0 ? 'suoyin' : list.letter">{{ list.letter }}</view>
								<view
									class="tui-list-cell"
									hover-class="tui-list-cell-hover"
									v-for="(item, index2) in list.data"
									:key="index2"
									@tap="selectCity(item)"
									:data-name="item.cityName"
									:hover-stay-time="150"
								>
									<view class="tui-list-cell-navigate" :class="[list.data.length - 1 == index ? 'last' : '']">{{ item.cityName }}</view>
								</view>
							</block>
						</view>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
		<view
			class="tui-indexed-list-bar"
			:style="{ height: indexBarHeight + 'px' }"
			@touchstart="touchStart"
			@touchmove.stop="touchMove"
			@touchend.stop="touchEnd"
			@touchcancel.stop="touchCancel"
			v-if="!inputVal"
		>
			<text v-for="(items, index) in curlist" :key="index" class="tui-indexed-list-text" :style="{ height: indexBarItemHeight + 'px' }">
				{{ index == 0 ? '索引' : items.letter }}
			</text>
		</view>
		<view class="tui-indexed-list-alert" v-if="touchmove && curlist[touchmoveIndex].letter">{{ curlist[touchmoveIndex].letter }}</view>
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import loactionmixin from '@/common/loactionmixin.js';
import zxNav from '@/components/zx-nav/zx-nav';
export default {
	data() {
		return {
			lists: [],
			touchmove: false, // 是否在索引表上滑动
			touchmoveIndex: -1,
			titleHeight: 0, // 索引二字距离窗口顶部的高度
			indexBarHeight: 0, // 索引表高度
			indexBarItemHeight: 0, // 索引表子项的高度
			scrollViewId: '', // scroll-view滚动到的子元素的id
			scrollViewPronId: '',
			winHeight: 0,
			inputShowed: false, // 输入框是否显示
			inputVal: '', // 搜索框输入的内容
			hotCity: [], // 热门城市
			searchResult: [], // 搜索城市的结果
			localCity: '',
			customTip: {
				notDetermined: '开启定位权限，花比三家为您提供配送服务。',
				denied: '开启定位权限，花比三家为您提供配送服务。',
				wxAppNotDenied: '微信未获得位置权限，请到设置中开启；开启定位，花比三家为您提供配送服务。',
				notEnabled: '系统定位未开启，请前往手机系统设置中开启；开启定位，花比三家为您提供配送服务。'
			},
			loactionTip: '',
			loadAddr: false,
			allcitylist: [],
			allprovincelist: [],
			currIndex: 0,
			province: ''
		};
	},
	onLoad: function(options) {
		const that = this;
		that.loactionTip = this.customTip[options.loactionTip];
		this.get_city();
		this.get_city(1);
		setTimeout(() => {
			uni.getSystemInfo({
				success: function(res) {
					console.log('res', res);
					let winHeight = res.windowHeight;
					let barHeight = winHeight - uni.upx2px(204) - res.statusBarHeight - 45;
					that.winHeight = winHeight - uni.upx2px(200) - res.statusBarHeight - 45;
					that.indexBarHeight = barHeight;
					that.indexBarItemHeight = barHeight / 25;
					that.titleHeight = uni.upx2px(132) + res.statusBarHeight + 45;
					// that.lists = cityData.list;
				}
			});
		}, 50);
	},
	mixins: [loactionmixin],
	computed: {
		...mapState(['currentLocation', 'locationCity']),
		curlist() {
			return this.currIndex == 0 ? this.allprovincelist : this.lists;
		}
	},
	components: { zxNav },
	methods: {
		...mapMutations(['SET_CURRENTLOCATION', 'SET_LOCATIONCITY']),
		showInput() {
			this.inputShowed = true;
		},
		clearInput() {
			this.inputVal = '';
			this.inputShowed = false;
			this.searchResult = [];
			uni.hideKeyboard(); //强行隐藏键盘
		},
		inputTyping(e) {
			this.inputVal = e.detail.value;
			this.searchCity();
		},
		// 搜索城市
		searchCity() {
			let result = [];
			this.allcitylist.forEach((item, index) => {
				if (item.keyword && item.keyword.indexOf(this.inputVal.toLocaleUpperCase()) !== -1) {
					result.push(item);
				}
			});
			console.log('result', result);
			this.searchResult = result;
		},
		//选择省份
		selectProvince(e) {
			this.currIndex = 1;
			this.province = e.cityName;
			let citylist = this.allcitylist.filter(item => item.pid == e.id);
			this.lists = this.groupArry(citylist);
		},
		// 选择城市
		selectCity(e) {
			//返回并刷新上一页面
			// this.$eventHub.$emit('emit', cityName);
			this.SET_CURRENTLOCATION(e);
			//如果上一页是提交表单页面，则返回两级
			let paths = getCurrentPages();
			let prepath = paths[paths.length - 2];
			uni.navigateBack({
				delta: prepath.route == 'pages/submitOrder/submitOrder' ? 2 : 1
			});
		},
		touchStart(e) {
			this.touchmove = true;
			let pageY = e.touches[0].pageY;
			let index = Math.floor((pageY - this.titleHeight) / this.indexBarItemHeight);
			let item = this.lists[index === 0 ? 1 : index];
			if (this.currIndex == 0) {
				item = this.allprovincelist[index === 0 ? 1 : index];
			}

			if (item) {
				if (this.currIndex == 0) {
					this.scrollViewPronId = item.letter;
				} else {
					this.scrollViewId = item.letter;
				}
				this.touchmoveIndex = index;
			}
		},
		touchMove(e) {
			let pageY = e.touches[0].pageY;
			let index = Math.floor((pageY - this.titleHeight) / this.indexBarItemHeight);
			let item = this.lists[index === 0 ? 1 : index];
			if (this.currIndex == 0) {
				item = this.allprovincelist[index === 0 ? 1 : index];
			}
			if (item) {
				if (this.currIndex == 0) {
					this.scrollViewPronId = item.letter;
				} else {
					this.scrollViewId = item.letter;
				}
				this.touchmoveIndex = index;
			}
		},
		touchEnd() {
			this.touchmove = false;
			this.touchmoveIndex = -1;
		},
		touchCancel() {
			this.touchmove = false;
			this.touchmoveIndex = -1;
		},
		get_city(province) {
			this.$postAction(
				this.$api.get_city,
				province
					? {
							province: 1
					  }
					: null
			).then(da => {
				if (da.code == 0 && da.data && da.data.length > 0) {
					if (province == 1) {
						this.allprovincelist = this.groupArry(da.data);
					} else {
						this.allcitylist = [...da.data];
					}
				}
			});
		},
		groupArry(arry) {
			//js 分组
			let obj = {},
				list = [];
			arry.forEach(item => {
				let letter = item.pinyin ? item.pinyin[0] : null;
				if (!obj[letter]) {
					obj[letter] = [];
				}
				item.cityName = this.currIndex == 0 ? item.province : item.city;
				obj[letter].push(item);
			});
			for (var key in obj) {
				list.push({
					letter: key,
					data: obj[key]
				});
			}
			list.sort((a, b) => {
				return a.letter > b.letter ? 1 : -1;
			});
			list.unshift({
				letter: 'A',
				data: []
			});
			if (list[list.length - 1].letter == 'null') {
				list[list.length - 1].letter = 'other';
			}
			return list;
		},

		changeSwiper(e) {
			this.currIndex = e.detail.current;
		},
		getLocationAuth() {
			var that = this;
			this.loadAddr = true;
			//wx.getSetting是获取用户授权的信息的，除了应用在位置信息授权还能应用在用户信息授权等等
			wx.getSetting({
				success: res => {
					// scope.userLocation  == undefined代表用户未授权且第一次登陆
					//console.log('检查地理位置信息是否授权', res.authSetting['scope.userLocation']);
					if (res.authSetting['scope.userFuzzyLocation'] == undefined) {
						console.log('hahah检查地理位置信息是否授权');
						that.getLoaction();
					}
					//小程序检测到用户不是第一次进入该页面,且未授权
					else if (res.authSetting['scope.userFuzzyLocation'] != undefined && res.authSetting['scope.userFuzzyLocation'] != true) {
						wx.openSetting({
							success: function(dataAu) {
								if (dataAu.authSetting['scope.userFuzzyLocation'] == true) {
									that.getLoaction();
								} else {
									that.loadAddr = false;
									that.loactionTip = that.customTip['wxAppNotDenied'];
								}
							}
						});
					} else if (res.authSetting['scope.userFuzzyLocation'] == true) {
						//授权后默认加载，直接获取定位
						that.getLoaction();
					}
				}
			});
		}
	}
};
</script>

<style>
page {
	height: 100%;
	overflow: hidden;
	background: #fff;
}

.page {
	height: 100%;
	overflow: hidden;
}

.scrollList {
	flex: 1;
}

.search-bar {
	display: flex;
	align-items: center;
	position: relative;
	padding: 27rpx 30rpx 0;
	background-color: #fff;
}

.search-bar-form {
	flex: 1;
	position: relative;
	border-radius: 32rpx;
	background: #f2f5f7;
}

.search-bar-box {
	display: flex;
	align-items: center;
	position: relative;
	padding-left: 20rpx;
	padding-right: 20rpx;
	height: 64rpx;
	z-index: 1;
}

.search-bar-input {
	line-height: normal;
	width: 100%;
	padding-left: 20rpx;
	font-size: 30rpx;
	color: #333;
}

.phcolor {
	font-size: 30rpx;
}

.icon-clear {
	height: 38rpx;
}

.icon-clear .tui-icon-class {
	display: block;
}

.search-bar-label {
	height: 64rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	position: absolute;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	z-index: 2;
	border-radius: 32rpx;
	color: #ccc;
	background: #f2f5f7;
}

.icon-search {
	position: relative;
	height: 26rpx;
	margin-right: 20rpx;
	font-size: inherit;
}

.search-bar-text {
	font-size: 30rpx;
	line-height: 32rpx;
}

.cancel-btn {
	padding-left: 30rpx;
}

.search-result::before {
	display: none;
}

.search-result::after {
	display: none;
}

.tui-list-cell {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
	width: 100%;
}

.tui-list-cell-hover {
	background-color: #eee !important;
}

.tui-list-cell-navigate {
	width: 100%;
	position: relative;
	padding: 30rpx 0 30rpx 30rpx;
	font-size: 28rpx;
	color: #333;
}

.tui-list-cell-navigate::after {
	content: '';
	position: absolute;
	border-bottom: 1rpx solid #eaeef1;
	-webkit-transform: scaleY(0.5);
	transform: scaleY(0.5);
	bottom: 0;
	right: 0;
	left: 30rpx;
}

.current-city {
	padding: 30rpx;
	background: #fff;
}

.tui-icon-class {
	margin-right: 10rpx;
}

.current-city .title {
	font-size: 24rpx;
	line-height: 24rpx;
	color: #999;
}

.city-name {
	display: flex;
	align-items: center;
	margin-left: 17rpx;
	font-size: 30rpx;
	font-weight: bold;
	line-height: 30rpx;
	color: #333;
}

.hot-city .title {
	height: 48rpx !important;
	padding-left: 30rpx;
	font-size: 24rpx !important;
	line-height: 48rpx !important;
	color: #999;
	background: #f2f5f7 !important;
}

.city-names {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
	align-content: space-between;
	width: 730rpx;
	padding: 12rpx 90rpx 26rpx 30rpx;
	background: #fff;
}

.city-name-item {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 140rpx;
	height: 56rpx;
	margin-top: 16rpx;
	/* border: solid 1rpx #ccc; */
	border-radius: 28rpx;
	font-size: 28rpx;
	color: #333;
	position: relative;
}

.city-name-item::before {
	content: '';
	position: absolute;
	width: 200%;
	height: 200%;
	-webkit-transform-origin: 0 0;
	transform-origin: 0 0;
	-webkit-transform: scale(0.5, 0.5);
	transform: scale(0.5, 0.5);
	-webkit-box-sizing: border-box;
	box-sizing: border-box;
	left: 0;
	top: 0;
	border-radius: 56rpx;
	border: 1px solid #ccc;
}

.tap-city {
	color: #fff;
	background: #5677fc;
	/* border: solid 1rpx #5677fc; */
}

.tui-list {
	background-color: #fff;
	position: relative;
	width: 100%;
	display: flex;
	flex-direction: column;
	padding-bottom: env(safe-area-inset-bottom);
}

.tui-list-cell-divider {
	height: 48rpx;
	padding-left: 30rpx;
	font-size: 24rpx;
	color: #999;
	background: #f2f5f7;
	padding: 0 30rpx;
	display: flex;
	align-items: center;
}

.tui-indexed-list-bar {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: flex-start;
	z-index: 9999;
	position: absolute;
	top: 260rpx;
	right: 0;
	padding-right: 10rpx;
	width: 44rpx;
}

.tui-indexed-list-text {
	font-size: 22rpx;
	white-space: nowrap;
}

.tui-indexed-list-bar.active {
	background-color: rgb(200, 200, 200);
}

.tui-indexed-list-alert {
	position: absolute;
	z-index: 20;
	width: 160rpx;
	height: 160rpx;
	left: 50%;
	top: 50%;
	margin-left: -80rpx;
	margin-top: -80rpx;
	border-radius: 80rpx;
	text-align: center;
	line-height: 160rpx;
	font-size: 70rpx;
	color: #fff;
	background-color: rgba(0, 0, 0, 0.5);
}
.selectAddr {
	border-bottom: 1rpx solid #eaeef1;
	padding: 30upx;
	background: #fff;
}
.selectAddr .item + .item {
	margin-left: 30upx;
}
</style>
